package com.qk.management.controller;


import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.entity.Business;
import com.qk.entity.Customer;
import com.qk.management.service.BusinessService;
import com.qk.management.service.CustomerService;
import com.qk.vo.business.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;


@RestController
@RequestMapping("/businesses")
public class BusinessController {


    @Autowired
    private BusinessService businessService;


    @Autowired
    private CustomerService customerService;


    @PostMapping
    public Result addBusiness(@RequestBody BusinessDTO businessdto) {
        businessService.addBusiness(businessdto);
        return Result.success();
    }

    @GetMapping
    public Result listBusiness(BusinessListDTO dto) {
        PageResult<BusinessDO> pageResult = businessService.listBusiness(dto);
        return Result.success(pageResult);
    }

    @PutMapping("/assign/{businessId}/{userId}")
    public Result updateBusinessById(@PathVariable Integer businessId, @PathVariable Integer userId) {
        businessService.updateById(Business.builder()
                .id(businessId)
                .userId(userId)
                .updateTime(LocalDateTime.now())
                .status(BusinessStatusConstants.WAIT_FOLLOW_UP)
                .build());
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getBusinessInfoById(@PathVariable Integer id){
        BusinessVO vo= businessService.getBusinessInfoById(id);
        return Result.success(vo);
    }

    @PutMapping("/back/{id}")
    public Result backBusiness(@PathVariable Integer id){
        businessService.updateById(Business.builder()
                .id(id)
                .updateTime(LocalDateTime.now())
                .status(BusinessStatusConstants.RECOVERY)
                .build());
        return Result.success();
    }


    //转客户功能
    @PostMapping("/toCustomer/{id}")
    public Result toCustomer(@PathVariable Integer id){
        Business business = businessService.getById(id);
        Customer customer = Customer.builder()
                .name(business.getName())
                .phone(business.getPhone())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        customerService.save(customer);
        businessService.removeById(id);
        return Result.success();
    }
}
